package com.dimeng;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;

import com.dimeng.adapter.MettleAdapter;
import com.dimeng.entity.MettlePhotoAlumb;
import com.dimeng.utils.AsyncImageLoader;
import com.dimeng.utils.Constant;
import com.dimeng.utils.LoadDataThread;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * @author write by ccn<br>
 * <b>helloandroid100@gmail.com</b>
 * @version 0.1;2012-7-2 下午3:00:37<br>
 * descrition: 
 */
public class MettleActivity extends SuperActivity {
	private static final long serialVersionUID = -6259654394129604807L;
	private GridView gridView;
	private MettleAdapter adapter;
	private List<MettlePhotoAlumb> list =  new ArrayList<MettlePhotoAlumb>();
	private String url = "";
	private Thread loadDataThread;
	private Gson gson = new Gson();
	
	private Map<String,List<MettlePhotoAlumb>> dataMap = new HashMap<String,List<MettlePhotoAlumb>>();
	String ablumId;
	private String alumb = "alumb";//相册
	private int alumbPN = 1;
	private int photosPN = 1;
	private int alumbSelection = 0;
	private int photoSelection = 0;
	
	private int alumbPosition = 0;
	private String type = alumb;
	private int resourceId = 0;
	private Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
				case 0:
	            	Toast.makeText(MettleActivity.this, "无数据更新", Toast.LENGTH_SHORT).show();
					break;
	            case 1:
					String json = (String) msg.obj;
					List<MettlePhotoAlumb> loadList = gson.fromJson(json, new TypeToken<List<MettlePhotoAlumb>>(){}.getType());
					List<MettlePhotoAlumb> dataList = dataMap.get(type);
					dataList = null == dataList ? new ArrayList<MettlePhotoAlumb>():dataList;
					dataList.addAll(loadList);
					dataMap.put(type, dataList);
					list.clear();
					list.addAll(dataList);
					adapter = new MettleAdapter(MettleActivity.this,list,gridView,resourceId);
					adapter.notifyDataSetChanged();
					gridView.setAdapter(adapter);
					if(alumb.equals(type)){
						gridView.setSelection(alumbSelection);
						++alumbPN;
						url = Constant.HOST_URL+"mettlePhotoAlum.do?pn="+alumbPN;
					} else {
						gridView.setSelection(photoSelection);
						++photosPN;
						url = Constant.HOST_URL+"mettlePhotos.do?ablumId="+ablumId.trim()+"&pn="+photosPN;
					}
	                break;
	            case 2:
	            	Toast.makeText(MettleActivity.this, Constant.NET_ERROR, Toast.LENGTH_LONG).show();
	            	break;
	            default:
	            	break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mettle_gridview);
		gridView = (GridView) findViewById(R.id.gridview);
		type = alumb;
		resourceId = R.layout.mettle_alumb_item;
		url = Constant.HOST_URL+"mettlePhotoAlum.do?pn="+alumbPN;
		startLoadDataThread(false);
		
		gridView.setOnItemClickListener(new OnItemClickListener() {
	        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
	        	MettlePhotoAlumb mettlePhotoAlumb = (MettlePhotoAlumb) gridView.getItemAtPosition(position);
	        	if(type.equals(alumb)){
	        		ablumId = mettlePhotoAlumb.getAblumId();
	        		if(null == ablumId || "".equals(ablumId))
	        			return;
	        		type = ablumId;
	        		resourceId = R.layout.mettle_photo_item;
	        		alumbPosition = position;
	        		
	        		photosPN = 1;
	        		photoSelection = 0;
	        		url = Constant.HOST_URL+"mettlePhotos.do?ablumId="+ablumId.trim()+"&pn="+photosPN;
	    			startLoadDataThread(true);
	        	} else {
	        		Intent intent = new Intent(MettleActivity.this,BrowseMettlePhotoActivity.class);
	        		Bundle b = new Bundle();
	        		b.putSerializable("photoList", (Serializable)list);
	        		b.putSerializable("alumbList", (Serializable) dataMap.get(alumb));
	        		b.putString("ablumId", ablumId);
	        		b.putInt("alumbPosition", alumbPosition);
	        		b.putInt("photoPosition", position);
	        		intent.putExtras(b);
	        		MettleActivity.this.startActivity(intent);
	        	}
	        }
	    });
		
		gridView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				if(OnScrollListener.SCROLL_STATE_IDLE == scrollState){
					if(alumb.equals(type))
						alumbSelection = gridView.getFirstVisiblePosition();
					else
						photoSelection = gridView.getFirstVisiblePosition();
				}
			}
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if((firstVisibleItem+visibleItemCount) == totalItemCount && totalItemCount > 6){
					startLoadDataThread(false);
				}
			}
		});
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if(KeyEvent.KEYCODE_BACK == keyCode && 0 == event.getRepeatCount() && !alumb.equals(type))
		{
			type = alumb;
			resourceId = R.layout.mettle_alumb_item;
			//把bitmap从内容中移除
			for(MettlePhotoAlumb mpa : list){
				String imageUrl = mpa.getImageUrl();
				Drawable drawable = AsyncImageLoader.getDrawableFromSoftRef(imageUrl);
				if (drawable != null) {// 如果缓存中包含此图则从缓存中获取
					Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
					bitmap.recycle();//释放内存
					bitmap = null;
					AsyncImageLoader.getImageCache().remove(imageUrl);
				}
			}
			
			list.clear();
			list.addAll(dataMap.get(type));
			adapter = new MettleAdapter(MettleActivity.this,list,gridView,resourceId);
			adapter.notifyDataSetChanged();
			gridView.setAdapter(adapter);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	public void startLoadDataThread(boolean isOpenCache){
		if(null == loadDataThread || !loadDataThread.isAlive()){
			loadDataThread = new LoadDataThread(url,Constant.CHARSET_GBK,handler,isOpenCache);
			loadDataThread.start();
		}
	}
}

